<template>
  <div class="finance-products-page">
    <!-- 头部 -->
    <div class="header-section">
      <div class="header-title">
        <el-icon class="title-icon"><Money /></el-icon>
        <h1>融资产品</h1>
      </div>
      <div class="header-subtitle">
        <p>专业的农业融资解决方案，助力您的农业发展</p>
      </div>
    </div>

    <!-- 融资产品列表 -->
    <div class="products-section">
      <el-card class="products-card">
        <template #header>
          <div class="products-header">
            <span class="products-title">融资产品列表</span>
            <div class="header-actions">
              <el-button @click="$router.push('/farmer/financingServer/myApplications')" class="view-applications-btn">
                <el-icon><List /></el-icon>
                我的申请
              </el-button>
            </div>
          </div>
        </template>

        <div class="products-list">
          <el-card
            v-for="product in financeProducts"
            :key="product.id"
            class="product-card"
            :class="getProductTypeClass(product.productType)"
          >
            <template #header>
              <div class="product-header">
                <div class="product-basic-info">
                  <div class="product-type">
                    <el-tag :type="getProductTypeTag(product.productType)" effect="light">
                      {{ getProductTypeText(product.productType) }}
                    </el-tag>
                    <el-tag v-if="product.allowJoint" type="success" effect="plain" size="small">
                      <el-icon><Connection /></el-icon>
                      支持联合融资
                    </el-tag>
                  </div>
                  <h3 class="product-name">{{ product.productName }}</h3>
                </div>
                <div class="product-actions">
                  <el-button
                    type="primary"
                    @click="handleApply(product)"
                    class="apply-product-btn"
                  >
                    <el-icon><Document /></el-icon>
                    立即申请
                  </el-button>
                </div>
              </div>
            </template>

            <div class="product-content">
              <div class="product-main-info">
                <!-- 利率信息 -->
                <div class="product-info-item">
                  <el-icon><TrendCharts /></el-icon>
                  <span class="info-label">利率：</span>
                  <span class="info-value rate">{{ (product.interestRate * 100).toFixed(2) }}%</span>
                </div>

                <!-- 贷款金额范围 -->
                <div class="product-info-item">
                  <el-icon><Coin /></el-icon>
                  <span class="info-label">贷款金额：</span>
                  <span class="info-value">
                    ¥{{ product.minAmount.toLocaleString() }} - ¥{{ product.maxAmount.toLocaleString() }}
                  </span>
                </div>

                <!-- 贷款期限 -->
                <div class="product-info-item">
                  <el-icon><Clock /></el-icon>
                  <span class="info-label">贷款期限：</span>
                  <span class="info-value">{{ product.termRange }}</span>
                </div>

                <!-- 适用农产品 -->
                <div class="product-info-item" v-if="product.applicableCrops">
                  <el-icon><Crop /></el-icon>
                  <span class="info-label">适用农产品：</span>
                  <span class="info-value crops">{{ product.applicableCrops }}</span>
                </div>

                <!-- 联合融资信息 -->
                <div class="product-info-item" v-if="product.allowJoint">
                  <el-icon><User /></el-icon>
                  <span class="info-label">联合融资：</span>
                  <span class="info-value">
                    支持，最少 {{ product.minJointMembers }} 人，最多 {{ product.maxJointMembers }} 人
                  </span>
                </div>
              </div>

              <!-- 产品描述 -->
              <div class="product-description">
                <p>{{ product.description }}</p>
              </div>

              <!-- 申请条件 -->
              <el-collapse class="requirements-collapse">
                <el-collapse-item title="申请条件">
                  <div class="requirements-content">
                    <p>{{ product.requirements }}</p>
                  </div>
                </el-collapse-item>
                <el-collapse-item title="申请流程">
                  <div class="process-content">
                    <ol>
                      <li v-for="(step, index) in product.applicationProcess.split('\n')" :key="index">
                        {{ step }}
                      </li>
                    </ol>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-card>
        </div>
      </el-card>
    </div>

    <!-- 融资申请对话框 -->
    <el-dialog
      v-model="showApplicationDialog"
      :title="applicationDialogTitle"
      width="900px"
      :close-on-click-modal="false"
      class="application-dialog"
      @close="handleDialogClose"
    >
      <el-form
        ref="applicationFormRef"
        :model="applicationForm"
        :rules="applicationRules"
        label-width="120px"
        class="application-form"
      >
        <!-- 选择融资产品 -->
        <el-form-item label="融资产品" prop="productId">
          <el-select
            v-model="applicationForm.productId"
            placeholder="请选择融资产品"
            style="width: 100%"
            @change="handleProductChange"
          >
            <el-option
              v-for="product in financeProducts"
              :key="product.id"
              :label="`${product.productName} (${getProductTypeText(product.productType)})`"
              :value="product.id"
            />
          </el-select>
        </el-form-item>

        <!-- 显示产品信息 -->
        <div v-if="selectedProduct" class="product-summary">
          <el-card shadow="never" class="summary-card">
            <div class="summary-content">
              <div class="summary-item">
                <span class="label">利率：</span>
                <span class="value rate">{{ (selectedProduct.interestRate * 100).toFixed(2) }}%</span>
              </div>
              <div class="summary-item">
                <span class="label">金额范围：</span>
                <span class="value">
                  ¥{{ selectedProduct.minAmount.toLocaleString() }} - ¥{{ selectedProduct.maxAmount.toLocaleString() }}
                </span>
              </div>
              <div class="summary-item">
                <span class="label">贷款期限：</span>
                <span class="value">{{ selectedProduct.termRange }}</span>
              </div>
              <div class="summary-item" v-if="selectedProduct.allowJoint">
                <span class="label">联合融资：</span>
                <span class="value">
                  {{ selectedProduct.minJointMembers }}-{{ selectedProduct.maxJointMembers }}人
                </span>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 融资类型选择 -->
        <el-form-item label="融资类型" prop="financeType">
          <el-radio-group v-model="applicationForm.financeType" @change="handleFinanceTypeChange">
            <el-radio :label="1">单独融资</el-radio>
            <el-radio :label="2" :disabled="!selectedProduct?.allowJoint">联合融资</el-radio>
          </el-radio-group>
          <div class="finance-type-tips">
            <p v-if="applicationForm.financeType === 1">
              💡 单独融资：申请金额需在产品的金额范围内，不能低于最低贷款金额，也不能高于最高贷款金额
            </p>
            <p v-else-if="applicationForm.financeType === 2">
              🤝 联合融资：申请金额可低于最低金额，您可以自己选择融资者，系统也可以为您匹配其他融资者
            </p>
            <p v-else-if="!selectedProduct?.allowJoint" class="disabled-tip">
              ❌ 该产品不支持联合融资
            </p>
          </div>
        </el-form-item>

        <!-- 申请金额 -->
        <el-form-item label="申请金额" prop="applyAmount">
          <el-input-number
            v-model="applicationForm.applyAmount"
            placeholder="请输入申请金额"
            :min="0"
            :precision="2"
            :step="1000"
            style="width: 200px;"
          />
          <span class="unit">元</span>
          <div class="amount-tips" v-if="selectedProduct">
            <template v-if="applicationForm.financeType === 1">
              <el-alert
                v-if="applicationForm.applyAmount && applicationForm.applyAmount < selectedProduct.minAmount"
                title="申请金额低于最低贷款金额，请选择联合融资或增加申请金额"
                type="warning"
                show-icon
                :closable="false"
                style="margin-top: 8px;"
              />
              <el-alert
                v-if="applicationForm.applyAmount && applicationForm.applyAmount > selectedProduct.maxAmount"
                title="申请金额超过最高贷款金额"
                type="error"
                show-icon
                :closable="false"
                style="margin-top: 8px;"
              />
            </template>
            <template v-else>
              <el-alert
                v-if="applicationForm.applyAmount && applicationForm.applyAmount > selectedProduct.maxAmount"
                title="申请金额超过最高贷款金额"
                type="error"
                show-icon
                :closable="false"
                style="margin-top: 8px;"
              />
              <el-alert
                v-else-if="applicationForm.applyAmount && applicationForm.applyAmount < selectedProduct.minAmount"
                title="联合融资允许申请金额低于最低贷款金额，系统将为您匹配其他融资者"
                type="info"
                show-icon
                :closable="false"
                style="margin-top: 8px;"
              />
            </template>
          </div>
        </el-form-item>

        <!-- 联合融资成员信息 -->
        <div v-if="applicationForm.financeType === 2 && selectedProduct" class="joint-finance-section">
          <div class="section-header">
            <h4>联合融资成员</h4>
            <span class="member-count">
              当前 {{ applicationForm.jointMembers.length }} 人 / 要求 {{ selectedProduct.minJointMembers }}-{{ selectedProduct.maxJointMembers }} 人
            </span>
          </div>
          
          <!-- 当前用户信息 -->
          <div class="current-user-member">
            <div class="member-info">
              <el-avatar :size="32" :src="currentUser.avatar" />
              <div class="member-details">
                <span class="member-name">{{ currentUser.name }} (我)</span>
                <span class="member-uid">UID: {{ currentUser.id }}</span>
              </div>
            </div>
            <div class="member-percentage">
              <el-input-number
                v-model="currentUserPercentage"
                :min="1"
                :max="100"
                :precision="0"
                controls-position="right"
                style="width: 120px;"
                @change="updateCurrentUserPercentage"
              />
              <span class="unit">%</span>
            </div>
          </div>

          <!-- 其他成员列表 -->
          <div class="other-members">
            <div
              v-for="(member, index) in applicationForm.jointMembers"
              :key="member.uid"
              class="joint-member-item"
            >
              <div class="member-info">
                <el-input
                  v-model="member.uid"
                  placeholder="请输入联合融资人UID"
                  style="width: 200px;"
                  @blur="validateMemberUid(member)"
                />
                <el-input-number
                  v-model="member.percentage"
                  :min="1"
                  :max="100"
                  :precision="0"
                  controls-position="right"
                  style="width: 120px; margin-left: 12px;"
                  placeholder="百分比"
                />
                <span class="unit">%</span>
              </div>
              <div class="member-actions">
                <el-button
                  type="danger"
                  text
                  @click="removeJointMember(index)"
                  :disabled="applicationForm.jointMembers.length <= selectedProduct.minJointMembers - 1"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>

          <!-- 添加成员按钮 -->
          <div class="add-member-section">
            <el-button
              type="primary"
              text
              @click="addJointMember"
              :disabled="applicationForm.jointMembers.length >= selectedProduct.maxJointMembers - 1"
            >
              <el-icon><Plus /></el-icon>
              添加联合融资人
            </el-button>
          </div>

          <!-- 百分比统计 -->
          <div class="percentage-summary">
            <div class="percentage-item">
              <span class="label">当前用户：</span>
              <span class="value">{{ currentUserPercentage }}%</span>
            </div>
            <div class="percentage-item">
              <span class="label">其他成员：</span>
              <span class="value">{{ otherMembersPercentage }}%</span>
            </div>
            <div class="percentage-item total">
              <span class="label">总计：</span>
              <span class="value" :class="{ 'error': totalPercentage !== 100 }">
                {{ totalPercentage }}%
              </span>
            </div>
            <el-alert
              v-if="totalPercentage !== 100"
              title="百分比总和必须等于100%"
              type="error"
              show-icon
              :closable="false"
              style="margin-top: 8px;"
            />
          </div>
        </div>

        <!-- 贷款用途 -->
        <el-form-item label="贷款用途" prop="purpose">
          <el-input
            v-model="applicationForm.purpose"
            type="textarea"
            :rows="3"
            placeholder="请详细说明贷款用途，这将有助于审核通过"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 凭证上传 -->
        <el-form-item label="申请凭证" prop="certificates">
          <el-upload
            v-model:file-list="applicationForm.certificates"
            action="#"
            multiple
            :limit="5"
            :before-upload="beforeCertificateUpload"
            :on-remove="handleCertificateRemove"
            :on-exceed="handleCertificateExceed"
            :on-preview="handleCertificatePreview"
            list-type="picture-card"
            accept="image/jpeg,image/png,image/gif,application/pdf"
            :file-list="applicationForm.certificates"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tips">
            支持 JPG、PNG、GIF、PDF 格式，单个文件不超过 5MB，最多上传 5 个文件
          </div>
        </el-form-item>

        <!-- 补充说明 -->
        <el-form-item label="补充说明">
          <el-input
            v-model="applicationForm.remarks"
            type="textarea"
            :rows="2"
            placeholder="可补充说明您的融资需求或其他相关信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleCancel" size="large">取消</el-button>
        <el-button
          type="primary"
          @click="submitApplication"
          :loading="submittingApplication"
          :disabled="!isApplicationValid"
          size="large"
        >
          提交申请
        </el-button>
      </template>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      :title="previewTitle"
      width="60%"
      center
    >
      <div class="preview-content">
        <img 
          v-if="previewImage" 
          :src="previewImage" 
          alt="预览图片" 
          class="preview-image"
        />
        <div v-else-if="previewFile" class="file-preview">
          <el-icon class="file-icon"><Document /></el-icon>
          <div class="file-info">
            <h4>{{ previewFile.name }}</h4>
            <p>文件类型: {{ previewFile.type }}</p>
            <p>文件大小: {{ formatFileSize(previewFile.size) }}</p>
          </div>
          <el-button type="primary" @click="downloadFile(previewFile)" class="download-btn">
            <el-icon><Download /></el-icon>
            下载文件
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Money, DocumentAdd, Document, TrendCharts, Coin, Clock, Crop, 
  Plus, List, Download, Connection, User, Delete
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const showApplicationDialog = ref(false)
const showPreviewDialog = ref(false)
const submittingApplication = ref(false)

const applicationFormRef = ref(null)
const selectedProduct = ref(null)
const previewImage = ref('')
const previewFile = ref(null)
const previewTitle = ref('')
const currentUserPercentage = ref(100)

// 当前用户信息
const currentUser = ref({
  id: 1001,
  name: '张大山',
  avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=100&h=100&fit=crop'
})

// 融资产品数据
const financeProducts = ref([
  {
    id: 1,
    productName: '农户信用贷',
    productType: 1,
    interestRate: 0.045,
    minAmount: 50000,
    maxAmount: 500000,
    termRange: '6个月-3年',
    applicableCrops: '粮食作物、经济作物、果蔬等',
    description: '专为农户设计的信用贷款产品，无需抵押，审批快速',
    requirements: '1. 具有完全民事行为能力；2. 有稳定的农业经营收入；3. 信用记录良好；4. 有明确的贷款用途',
    applicationProcess: '在线申请\n提交材料\n信用评估\n审批放款',
    allowJoint: true,
    minJointMembers: 2,
    maxJointMembers: 5
  },
  {
    id: 2,
    productName: '农产品抵押贷',
    productType: 2,
    interestRate: 0.038,
    minAmount: 100000,
    maxAmount: 1000000,
    termRange: '1年-5年',
    applicableCrops: '高价值农产品、仓储农产品',
    description: '以农产品作为抵押物的贷款产品，额度高，利率优惠',
    requirements: '1. 拥有可抵押的农产品；2. 农产品价值评估达标；3. 有完整的产销记录；4. 提供抵押物保管证明',
    applicationProcess: '提交申请\n抵押物评估\n签订合同\n办理抵押登记\n放款',
    allowJoint: true,
    minJointMembers: 3,
    maxJointMembers: 8
  },
  {
    id: 3,
    productName: '农业合作社担保贷',
    productType: 3,
    interestRate: 0.042,
    minAmount: 200000,
    maxAmount: 2000000,
    termRange: '1年-3年',
    applicableCrops: '所有农产品类型',
    description: '由农业合作社提供担保的贷款产品，适合合作社成员',
    requirements: '1. 农业合作社正式成员；2. 合作社提供担保；3. 有明确的经营计划；4. 合作社推荐信',
    applicationProcess: '合作社推荐\n提交申请\n担保审核\n审批放款',
    allowJoint: false,
    minJointMembers: 1,
    maxJointMembers: 1
  },
  {
    id: 4,
    productName: '设备融资租赁',
    productType: 4,
    interestRate: 0.048,
    minAmount: 50000,
    maxAmount: 300000,
    termRange: '1年-5年',
    applicableCrops: '所有农产品类型',
    description: '专为农业设备采购设计的融资产品',
    requirements: '1. 设备采购合同；2. 设备使用计划；3. 还款能力证明',
    applicationProcess: '提交申请\n设备评估\n签订合同\n放款',
    allowJoint: true,
    minJointMembers: 2,
    maxJointMembers: 4
  }
])

// 申请表单数据
const applicationForm = reactive({
  productId: null,
  financeType: 1,
  applyAmount: null,
  purpose: '',
  certificates: [],
  remarks: '',
  jointMembers: [] // 联合融资成员
})

// 表单验证规则
const applicationRules = {
  productId: [
    { required: true, message: '请选择融资产品', trigger: 'change' }
  ],
  financeType: [
    { required: true, message: '请选择融资类型', trigger: 'change' }
  ],
  applyAmount: [
    { required: true, message: '请输入申请金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '申请金额必须大于0', trigger: 'blur' }
  ],
  purpose: [
    { required: true, message: '请输入贷款用途', trigger: 'blur' },
    { min: 10, max: 500, message: '贷款用途长度为10-500个字符', trigger: 'blur' }
  ],
  certificates: [
    { required: true, message: '请上传申请凭证', trigger: 'change' },
    { type: 'array', min: 1, message: '至少上传一个凭证文件', trigger: 'change' }
  ]
}

// 计算属性
const applicationDialogTitle = computed(() => {
  return selectedProduct.value ? `申请 ${selectedProduct.value.productName}` : '融资申请'
})

const otherMembersPercentage = computed(() => {
  return applicationForm.jointMembers.reduce((sum, member) => sum + (member.percentage || 0), 0)
})

const totalPercentage = computed(() => {
  return currentUserPercentage.value + otherMembersPercentage.value
})

const isApplicationValid = computed(() => {
  if (!selectedProduct.value || !applicationForm.applyAmount) return false
  
  // 金额验证
  let amountValid = true
  if (applicationForm.financeType === 1) {
    // 单独融资：金额必须在范围内
    amountValid = applicationForm.applyAmount >= selectedProduct.value.minAmount && 
                  applicationForm.applyAmount <= selectedProduct.value.maxAmount
  } else {
    // 联合融资：金额不能超过最高限额
    amountValid = applicationForm.applyAmount <= selectedProduct.value.maxAmount
  }
  
  // 联合融资额外验证
  if (applicationForm.financeType === 2) {
    const membersValid = applicationForm.jointMembers.length >= selectedProduct.value.minJointMembers - 1 &&
                        applicationForm.jointMembers.length <= selectedProduct.value.maxJointMembers - 1
    const percentageValid = totalPercentage.value === 100
    const membersFilled = applicationForm.jointMembers.every(member => 
      member.uid && member.percentage && member.percentage > 0
    )
    
    return amountValid && membersValid && percentageValid && membersFilled
  }
  
  return amountValid
})

// 方法
const getProductTypeText = (type) => {
  const types = { 1: '信用贷', 2: '抵押贷', 3: '担保贷', 4: '设备贷' }
  return types[type] || '未知类型'
}

const getProductTypeTag = (type) => {
  const tags = { 1: 'success', 2: 'warning', 3: 'primary', 4: 'info' }
  return tags[type] || 'info'
}

const getProductTypeClass = (type) => {
  const classes = { 1: 'credit-product', 2: 'mortgage-product', 3: 'guarantee-product', 4: 'equipment-product' }
  return classes[type] || ''
}

const handleProductChange = (productId) => {
  selectedProduct.value = financeProducts.value.find(p => p.id === productId)
  // 重置金额验证和联合融资数据
  if (applicationFormRef.value) {
    applicationFormRef.value.clearValidate('applyAmount')
  }
  // 如果产品不支持联合融资，自动切换到单独融资
  if (!selectedProduct.value.allowJoint && applicationForm.financeType === 2) {
    applicationForm.financeType = 1
  }
  resetJointMembers()
}

const handleFinanceTypeChange = (type) => {
  if (type === 2) {
    resetJointMembers()
  } else {
    applicationForm.jointMembers = []
  }
}

const resetJointMembers = () => {
  if (selectedProduct.value && applicationForm.financeType === 2) {
    // 初始化最少成员数
    const initialMembersCount = Math.max(0, selectedProduct.value.minJointMembers - 1)
    applicationForm.jointMembers = Array.from({ length: initialMembersCount }, () => ({
      uid: '',
      percentage: 0
    }))
    // 重置当前用户百分比
    currentUserPercentage.value = 100 - (initialMembersCount * Math.floor(100 / selectedProduct.value.minJointMembers))
  } else {
    applicationForm.jointMembers = []
    currentUserPercentage.value = 100
  }
}

const updateCurrentUserPercentage = () => {
  // 确保当前用户百分比合理
  if (currentUserPercentage.value < 1) currentUserPercentage.value = 1
  if (currentUserPercentage.value > 100) currentUserPercentage.value = 100
}

const addJointMember = () => {
  if (applicationForm.jointMembers.length < selectedProduct.value.maxJointMembers - 1) {
    applicationForm.jointMembers.push({
      uid: '',
      percentage: 0
    })
  }
}

const removeJointMember = (index) => {
  if (applicationForm.jointMembers.length > selectedProduct.value.minJointMembers - 1) {
    applicationForm.jointMembers.splice(index, 1)
  }
}

const validateMemberUid = (member) => {
  if (member.uid && member.uid === currentUser.value.id.toString()) {
    ElMessage.warning('不能添加自己作为联合融资人')
    member.uid = ''
  }
}

const handleApply = (product) => {
  showApplicationDialog.value = true
  applicationForm.productId = product.id
  selectedProduct.value = product
  resetJointMembers()
}

const handleCancel = () => {
  showApplicationDialog.value = false
  resetApplicationForm()
}

const handleDialogClose = () => {
  resetApplicationForm()
}

const beforeCertificateUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isPDF = file.type === 'application/pdf'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage && !isPDF) {
    ElMessage.error('文件格式只能是图片或PDF!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过 5MB!')
    return false
  }

  // 为文件添加唯一ID
  file.uid = Date.now() + Math.random()
  
  return true
}

const handleCertificateRemove = (file, fileList) => {
  applicationForm.certificates = fileList
}

const handleCertificateExceed = (files, fileList) => {
  ElMessage.warning(`最多只能上传 5 个文件，已选择 ${files.length} 个文件，共 ${files.length + fileList.length} 个文件`)
}

const handleCertificatePreview = (file) => {
  if (file.type && file.type.startsWith('image/')) {
    // 图片预览
    previewImage.value = file.url || URL.createObjectURL(file.raw)
    previewTitle.value = '图片预览'
    showPreviewDialog.value = true
  } else {
    // 文档预览
    previewFile.value = file
    previewTitle.value = '文档信息'
    showPreviewDialog.value = true
  }
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const downloadFile = (file) => {
  if (file.url) {
    // 如果文件有URL，直接下载
    const link = document.createElement('a')
    link.href = file.url
    link.download = file.name
    link.click()
  } else if (file.raw) {
    // 如果是新上传的文件，创建下载链接
    const url = URL.createObjectURL(file.raw)
    const link = document.createElement('a')
    link.href = url
    link.download = file.name
    link.click()
    URL.revokeObjectURL(url)
  }
}

const submitApplication = async () => {
  if (!applicationFormRef.value) return
  
  try {
    await applicationFormRef.value.validate()
    
    if (!isApplicationValid.value) {
      ElMessage.error('申请信息不符合要求，请检查后重新提交')
      return
    }
    
    submittingApplication.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 获取本地存储的申请记录
    const storedApplications = JSON.parse(localStorage.getItem('financeApplications') || '[]')
    
    // 创建新的申请记录
    const newApplication = {
      id: Date.now(),
      productId: applicationForm.productId,
      productName: selectedProduct.value.productName,
      productType: selectedProduct.value.productType,
      financeType: applicationForm.financeType,
      applyAmount: applicationForm.applyAmount,
      purpose: applicationForm.purpose,
      certificates: applicationForm.certificates.map(file => ({
        name: file.name,
        type: file.type,
        size: file.size,
        url: file.url || URL.createObjectURL(file.raw)
      })),
      remarks: applicationForm.remarks,
      applyTime: new Date().toISOString(),
      status: 0,
      jointStatus: applicationForm.financeType === 2 ? 1 : 0,
      jointMembers: applicationForm.financeType === 2 ? [
        {
          uid: currentUser.value.id,
          name: currentUser.value.name,
          percentage: currentUserPercentage.value,
          isCurrentUser: true
        },
        ...applicationForm.jointMembers.map(member => ({
          uid: member.uid,
          name: `用户${member.uid}`,
          percentage: member.percentage,
          isCurrentUser: false,
          matched: !member.uid // 如果没有填写UID，表示需要系统匹配
        }))
      ] : []
    }
    
    // 保存到本地存储
    storedApplications.unshift(newApplication)
    localStorage.setItem('financeApplications', JSON.stringify(storedApplications))
    
    ElMessage.success('融资申请提交成功，请等待审核')
    showApplicationDialog.value = false
    resetApplicationForm()
    
    // 跳转到我的申请页面
    router.push('/farmer/financingServer/myApplications')
  } catch (error) {
    console.error('提交申请失败:', error)
  } finally {
    submittingApplication.value = false
  }
}

const resetApplicationForm = () => {
  Object.assign(applicationForm, {
    productId: null,
    financeType: 1,
    applyAmount: null,
    purpose: '',
    certificates: [],
    remarks: '',
    jointMembers: []
  })
  selectedProduct.value = null
  currentUserPercentage.value = 100
  if (applicationFormRef.value) {
    applicationFormRef.value.clearValidate()
  }
}

onMounted(() => {
  // 页面加载时的初始化逻辑
})
</script>

<style scoped>
.finance-products-page {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  min-height: 100vh;
}

/* 头部样式 */
.header-section {
  text-align: center;
  margin-bottom: 32px;
  padding: 40px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  color: white;
}

.header-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  margin-bottom: 12px;
}

.title-icon {
  font-size: 40px;
}

.header-title h1 {
  margin: 0;
  font-size: 36px;
  font-weight: 700;
}

.header-subtitle p {
  margin: 0;
  font-size: 18px;
  opacity: 0.9;
}

/* 产品区域 */
.products-section {
  margin-bottom: 32px;
}

.products-card {
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.products-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.products-title {
  font-size: 20px;
  font-weight: 600;
  color: #2d3748;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.view-applications-btn {
  padding: 10px 24px;
  border-radius: 12px;
  font-weight: 600;
}

/* 产品列表 - 垂直排列 */
.products-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.product-card {
  border-radius: 12px;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  margin-bottom: 16px;
}

.product-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.product-card.credit-product {
  border-color: #67c23a;
}

.product-card.mortgage-product {
  border-color: #e6a23c;
}

.product-card.guarantee-product {
  border-color: #409eff;
}

.product-card.equipment-product {
  border-color: #909399;
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16px;
}

.product-basic-info {
  flex: 1;
}

.product-type {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.product-name {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
}

.product-actions {
  flex-shrink: 0;
}

/* 产品内容 */
.product-content {
  padding: 8px 0;
}

.product-main-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.product-info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.product-info-item .el-icon {
  color: #667eea;
  font-size: 16px;
}

.info-label {
  color: #718096;
  font-weight: 500;
  min-width: 80px;
}

.info-value {
  color: #2d3748;
  font-weight: 600;
}

.info-value.rate {
  color: #e53e3e;
  font-size: 16px;
}

.info-value.crops {
  color: #38a169;
}

.product-description {
  margin: 16px 0;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.product-description p {
  margin: 0;
  color: #4a5568;
  line-height: 1.5;
}

.requirements-collapse {
  margin-top: 16px;
}

.requirements-content,
.process-content {
  padding: 8px 0;
  color: #4a5568;
  line-height: 1.6;
}

.process-content ol {
  margin: 0;
  padding-left: 20px;
}

.process-content li {
  margin-bottom: 4px;
}

/* 对话框样式 */
.application-dialog {
  border-radius: 16px;
}

.application-form {
  padding: 20px 0;
}

.product-summary {
  margin-bottom: 20px;
}

.summary-card {
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.summary-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.summary-item .label {
  color: #718096;
  font-size: 14px;
}

.summary-item .value {
  color: #2d3748;
  font-weight: 600;
}

.summary-item .value.rate {
  color: #e53e3e;
}

.finance-type-tips {
  margin-top: 8px;
  padding: 12px;
  background: #f0f9ff;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.finance-type-tips p {
  margin: 0;
  color: #4a5568;
  font-size: 14px;
}

.finance-type-tips .disabled-tip {
  color: #f56c6c;
}

.unit {
  margin-left: 8px;
  color: #718096;
}

.amount-tips {
  margin-top: 8px;
}

.upload-tips {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}

/* 联合融资样式 */
.joint-finance-section {
  margin: 20px 0;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e2e8f0;
}

.section-header h4 {
  margin: 0;
  color: #2d3748;
  font-size: 16px;
  font-weight: 600;
}

.member-count {
  color: #718096;
  font-size: 14px;
}

.current-user-member {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
  margin-bottom: 12px;
}

.member-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.member-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.member-name {
  font-weight: 600;
  color: #2d3748;
}

.member-uid {
  font-size: 12px;
  color: #718096;
}

.member-percentage {
  display: flex;
  align-items: center;
  gap: 8px;
}

.other-members {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.joint-member-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.member-actions {
  flex-shrink: 0;
}

.add-member-section {
  text-align: center;
  margin-bottom: 16px;
}

.percentage-summary {
  padding: 16px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.percentage-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.percentage-item.total {
  border-top: 1px solid #e2e8f0;
  margin-top: 8px;
  padding-top: 12px;
  font-weight: 600;
}

.percentage-item .value.error {
  color: #f56c6c;
}

/* 文件预览样式 */
.preview-content {
  text-align: center;
  padding: 20px;
}

.preview-image {
  max-width: 100%;
  max-height: 60vh;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.file-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 40px;
}

.file-icon {
  font-size: 80px;
  color: #409eff;
}

.file-info {
  text-align: center;
}

.file-info h4 {
  margin: 0 0 12px 0;
  color: #2d3748;
  font-size: 18px;
}

.file-info p {
  margin: 8px 0;
  color: #718096;
}

.download-btn {
  margin-top: 20px;
}

/* 自定义上传列表样式 */
:deep(.el-upload-list--picture-card) {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
  border-radius: 8px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
  object-fit: cover;
}

:deep(.el-upload-list--picture-card .el-upload-list__item-actions) {
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .finance-products-page {
    padding: 16px;
  }
  
  .header-title {
    flex-direction: column;
    gap: 8px;
  }
  
  .header-title h1 {
    font-size: 28px;
  }
  
  .product-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .product-main-info {
    grid-template-columns: 1fr;
  }
  
  .products-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .current-user-member,
  .joint-member-item {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .member-percentage {
    width: 100%;
    justify-content: flex-start;
  }
  
  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 80px;
    height: 80px;
  }
}
</style>